import {createContext, useContext, useReducer} from "react";

const initialTasks = [
    { id: 0, text: 'Philosopher’s Path', done: true },
    { id: 1, text: 'Visit the temple', done: false },
    { id: 2, text: 'Drink match', done: false }
];

export const TasksContext = createContext(null);
export const TasksDispatchContext = createContext(null);

export function useTasks() {
    return useContext(TasksContext)
}

export function useTasksDispatch() {
    return useContext(TasksDispatchContext)
}

export default function TasksProvider({children}) {
    const [tasks, dispatch] = useReducer(
        tasksReducer,
        initialTasks
    );

    return (
        <TasksContext.Provider value={tasks}>
            <TasksDispatchContext.Provider value={dispatch}>
                {children}
            </TasksDispatchContext.Provider>
        </TasksContext.Provider>
    )
}

function tasksReducer(tasks, action) {
    switch (action.type) {
        case 'added': {
            // 找到最大的ID，实际会用数据库默认自增ID
            let nextId = tasks.filter(t => t.id !== undefined).reduce((pre, cur) => {
                return pre.id < cur.id ? pre.id : cur.id
            })
            nextId++;
            return [
                ...tasks,
                {
                    id: nextId,
                    text: action.text,
                    done: false
                }
            ]
        }
        case 'changed': {
            return tasks.map(t => {
                if (t.id === action.task.id) {
                    return action.task
                } else {
                    return t
                }
            })
        }
        case 'deleted': {
            return tasks.filter(t => t.id !== action.id)
        }
        default: {
            throw Error('Unknown action:' + action.type)
        }
    }
}